#include "comm.hpp"
#include "log.hpp"

int main()
{
    Init init;
    key_t key = ftok(PATH_NAME, proj_ID);
    if (key == -1)
    {
        // perror("service ftok");
        logMessage(FATAL, "%s [%s][%d]", "service ftok fatal", __FILE__, __LINE__);
        exit(1);
    }

    // 创建共享内存
    int shmid = shmget(key, SIZE, IPC_CREAT | IPC_EXCL | 0666);
    if (shmid == -1)
    {
        // perror("service shmget");
        logMessage(ERROR, "%s [%s][%d]", "service shmget error", __FILE__, __LINE__);
        exit(2);
    }
    logMessage(NORMAL, "%s [%s][%d]", "service shmget success", __FILE__, __LINE__);

    // 挂接共享内存
    char *shmaddr = (char *)shmat(shmid, nullptr, 0);
    logMessage(NORMAL, "%s [%s][%d]", "service shmat success", __FILE__, __LINE__);

    // 发送逻辑
    // int count=10;
    int fd = OpenFifo(FIFO_NAME, WEITE);
    while (true)
    {
        ssize_t s = read(0, shmaddr, SIZE - 1);
        if (s > 0)
        {
            shmaddr[s - 1] = '\0';
            Signal(fd);
            logMessage(NORMAL, "%s %s [%s][%d]", "service send success", shmaddr, __FILE__, __LINE__);
            if (strcmp(shmaddr, "quit") == 0)
            {
                break;
            }
        }
        // if(!count--)
        // {
        //     break;
        // }
        // sleep(1);
    }

    // 取消挂接共享内存
    int n = shmdt(shmaddr);
    if (n == -1)
    {
        // perror("service shmdt");
        logMessage(ERROR, "%s [%s][%d]", "service shmdt error", __FILE__, __LINE__);
        exit(3);
    }
    logMessage(NORMAL, "%s [%s][%d]", "service shmdt success", __FILE__, __LINE__);
    // 释放共享内存
    n = shmctl(shmid, IPC_RMID, nullptr);
    if (n == -1)
    {
        // perror("service shmctl");
        logMessage(ERROR, "%s [%s][%d]", "service shmctl error", __FILE__, __LINE__);
        exit(4);
    }
    logMessage(NORMAL, "%s [%s][%d]", "service shmctl success", __FILE__, __LINE__);
    CloseFifo(fd);
    return 0;
}